package com.tools.web.interceptor.limiting;

import com.tools.common.object.Note;
import com.tools.common.thread.Timeunit;
import com.tools.middle.redis.client.JedisClusterPlus;
import com.tools.web.interceptor.auth.AuthenticationManager;

/**
 * 使用 JedisClusterPlus 客户端操作集群 Redis 实现的限流拦截器
 * */
@Note("使用 JedisClusterPlus 客户端操作集群 Redis 实现的限流拦截器")
public final class JedisClusterPlusReqLimitInterceptor extends RequestLimitInterceptor {

    @Note("JedisClusterPlus 操作集群 Redis 的客户端")
    private final JedisClusterPlus cache;

    public JedisClusterPlusReqLimitInterceptor(JedisClusterPlus cache, RequestLimitSource source) {
        this(cache, source, null);
    }

    public JedisClusterPlusReqLimitInterceptor(JedisClusterPlus cache, RequestLimitSource source,
                                               AuthenticationManager authenticationManager) {
        super(source, cache != null, "JedisClusterPlus 客户端实例为 null", authenticationManager);
        this.cache = cache;
    }

    @Override
    protected Timeunit protected_getImplSelfTimeunit() {
        return Timeunit.SECOND;
    }

    @Override
    protected Integer protected_getRequestedCount(String key) {
        String s = this.cache.jedisCluster().get(key);
        return (s == null) ? null : Integer.parseInt(s);
    }

    @Override
    protected void protected_setRequestedCount(String key, int count, long expiration, Timeunit timeunit) {
        this.cache.jedisCluster().setex(key, Timeunit.toSecond(expiration, timeunit), Integer.toString(count));
    }

    @Override
    protected long protected_getRemainder(String key) {
        return this.cache.ttl(key);
    }

    @Override
    protected void protected_removeRequestCount(String key) {
        this.cache.jedisCluster().del(key);
    }
}
